import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'http_dio.dart';
class RetryOnConnectionChangeInterceptor extends Interceptor {
  final Connectivity _connectivity = Connectivity();

  @override
  Future onError(DioException err, ErrorInterceptorHandler handler) async {
    if (_shouldRetry(err)) {
      try {
        // 等待网络恢复
        await _connectivity.onConnectivityChanged.firstWhere(
              (result) => result != ConnectivityResult.none,
        );

        // 重试请求
        final response = await HttpManager().getDio.fetch(err.requestOptions);
        return handler.resolve(response);
      } catch (e) {
        return handler.next(err);
      }
    }
    return handler.next(err);
  }

  bool _shouldRetry(DioException err) {
    return err.type == DioExceptionType.connectionTimeout ||
        err.type == DioExceptionType.receiveTimeout ||
        err.type == DioExceptionType.sendTimeout ||
        err.type == DioExceptionType.connectionError;
  }
}